﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;
using VOL.demo.IRepositories.ReturnOrder;
using VOL.demo.IServices.wms.ReturnOrder;
using VOL.Entity.DomainModels;

namespace VOL.demo.Services.wms.ReturnOrder
{
    public class ReturnOrderServices : IReturnOrderIServices
    { 
        private readonly IReturnOrderIRepository _repository;

        public ReturnOrderServices(IReturnOrderIRepository repository)
        {
            _repository = repository;
        }

        /// <summary>
        /// 分页查询退货单
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页记录数</param>
        /// <param name="whereExpression">查询条件</param>
        /// <returns>分页结果</returns>
        public async Task<(List<returnordermodel> Data, int TotalCount)> GetPageListAsync(int pageIndex, int pageSize, 
            Expression<Func<returnordermodel, bool>> whereExpression = null)
        {
            // 页码从1开始，但SqlSugar分页从0开始，需要转换
            int sqlSugarPageIndex = pageIndex <= 0 ? 0 : pageIndex - 1;
            
            return await _repository.GetPageListAsync(sqlSugarPageIndex, pageSize, whereExpression);
        }

        /// <summary>
        /// 根据ID获取退货单
        /// </summary>
        /// <param name="id">退货单ID</param>
        /// <returns>退货单信息</returns>
        public async Task<returnordermodel> GetByIdAsync(long id)
        {
            return await _repository.GetByIdAsync(id);
        }

        /// <summary>
        /// 更新退货单
        /// </summary>
        /// <param name="entity">退货单实体</param>
        /// <returns>更新结果</returns>
        public async Task<bool> UpdateAsync(returnordermodel entity)
        {
            // 更新前进行数据验证
            if (entity == null)
            {
                return false;
            }

            // 设置修改时间和修改人信息
            entity.ModifyDate = DateTime.Now;
            
            // 可以在这里添加其他业务逻辑，例如验证状态等
            
            return await _repository.UpdateAsync(entity);
        }

        /// <summary>
        /// 删除退货单
        /// </summary>
        /// <param name="id">退货单ID</param>
        /// <returns>删除结果</returns>
        public async Task<bool> DeleteAsync(long id)
        {
            // 删除前可以进行业务验证，例如检查是否有关联数据
            var entity = await _repository.GetByIdAsync(id);
            if (entity == null)
            {
                return false;
            }
            
            // 可以在这里添加其他业务逻辑，例如验证状态是否允许删除
            // 例如：已审核的订单不允许删除
            if (entity.Status != null && entity.Status > 1)
            {
                // 这里可以抛出异常或返回false
                return false;
            }
            
            return await _repository.DeleteAsync(id);
        }

        /// <summary>
        /// 批量删除退货单
        /// </summary>
        /// <param name="ids">退货单ID列表</param>
        /// <returns>删除结果</returns>
        public async Task<bool> DeleteRangeAsync(long[] ids)
        {
            if (ids == null || ids.Length == 0)
            {
                return false;
            }
            
            // 可以在这里添加批量删除前的业务验证逻辑
            // 例如：检查这些订单是否都允许删除
            
            return await _repository.DeleteRangeAsync(ids);
        }

        /// <summary>
        /// 获取退货单联查结果（包含供应商名称、部门名称、客户名称）
        /// </summary>
        /// <param name="id">退货单ID</param>
        /// <returns>退货单联查结果</returns>
        public async Task<ReturnOrderWithRelations> GetWithRelationsAsync(long id)
        {
            return await _repository.GetWithRelationsAsync(id);
        }
        
        /// <summary>
        /// 获取进货单联查列表（包含供应商名称、部门名称、客户名称）
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页记录数</param>
        /// <returns>分页结果</returns>
        public async Task<(List<PurchaseOrderWithRelation> Data, int TotalCount)> GetPurchaseOrderListAsync(int pageIndex, int pageSize)
        {
            // 页码从1开始，但SqlSugar分页从0开始，需要转换
            int sqlSugarPageIndex = pageIndex <= 0 ? 0 : pageIndex - 1;
            
            return await _repository.GetPurchaseOrderListAsync(sqlSugarPageIndex, pageSize);
        }
        
        /// <summary>
        /// 根据进货单编号获取进货单信息（包含供应商、联系人、联系方式、部门、进货人）
        /// </summary>
        /// <param name="orderCode">进货单编号</param>
        /// <returns>进货单信息</returns>
        public async Task<PurchaseOrderWithRelation> GetPurchaseOrderByCodeAsync(string orderCode)
        {
            if (string.IsNullOrEmpty(orderCode))
            {
                return null;
            }
            
            return await _repository.GetPurchaseOrderByCodeAsync(orderCode);
        }
        
        /// <summary>
        /// 根据进货单号获取进货明细列表（包含货品信息）
        /// </summary>
        /// <param name="orderCode">进货单号</param>
        /// <returns>进货明细列表</returns>
        public async Task<List<PurchaseOrderItemWithProductModel>> GetPurchaseOrderItemsByCodeAsync(string orderCode)
        {
            if (string.IsNullOrEmpty(orderCode))
            {
                return new List<PurchaseOrderItemWithProductModel>();
            }
            
            return await _repository.GetPurchaseOrderItemsByCodeAsync(orderCode);
        }

        /// <summary>
        /// 分页查询退货单联查结果（包含供应商名称、部门名称、客户名称）
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页记录数</param>
        /// <param name="whereExpression">查询条件</param>
        /// <returns>分页结果</returns>
        public async Task<(List<ReturnOrderWithRelations> Data, int TotalCount)> GetPageListWithRelationsAsync(
            int pageIndex, 
            int pageSize, 
            Expression<Func<returnordermodel, bool>> whereExpression = null)
        {
            // 页码从1开始，但SqlSugar分页从0开始，需要转换
            int sqlSugarPageIndex = pageIndex <= 0 ? 0 : pageIndex - 1;
            
            return await _repository.GetPageListWithRelationsAsync(sqlSugarPageIndex, pageSize, whereExpression);
        }
        /// <summary>
        /// 添加退货单和退货明细（使用DTO，自动设置系统字段）
        /// </summary>
        /// <param name="createDto">退货单和退货明细创建DTO</param>
        /// <returns>添加结果</returns>
        public async Task<bool> AddWithDetailsAsync(ReturnOrderWithDetailsCreateDto createDto)
        {
            try
            {
                Console.WriteLine("=== Service层开始处理 ===");
                
                // 基础验证
                if (createDto == null)
                {
                    Console.WriteLine("Service验证失败: createDto为null");
                    return false;
                }
                
                if (createDto.ReturnOrder == null)
                {
                    Console.WriteLine("Service验证失败: ReturnOrder为null");
                    return false;
                }
                
                if (createDto.ReturnOrderDetails == null || !createDto.ReturnOrderDetails.Any())
                {
                    Console.WriteLine("Service验证失败: ReturnOrderDetails为null或空");
                    return false;
                }

                Console.WriteLine($"退货单号: {createDto.ReturnOrder.ReturnOrderCode}");
                Console.WriteLine($"进货单号: {createDto.ReturnOrder.PurchaseOrderCode}");
                Console.WriteLine($"退货明细数量: {createDto.ReturnOrderDetails.Count}");

                // 业务验证
                // 1. 检查进货单号是否存在
                if (!string.IsNullOrEmpty(createDto.ReturnOrder.PurchaseOrderCode))
                {
                    Console.WriteLine($"检查进货单号: {createDto.ReturnOrder.PurchaseOrderCode}");
                    try
                    {
                        var purchaseOrder = await _repository.GetPurchaseOrderByCodeAsync(createDto.ReturnOrder.PurchaseOrderCode);
                        if (purchaseOrder == null)
                        {
                            Console.WriteLine($"验证失败: 进货单号 {createDto.ReturnOrder.PurchaseOrderCode} 不存在");
                            return false;
                        }
                        Console.WriteLine($"进货单验证通过: ID={purchaseOrder.Id}, 供应商={purchaseOrder.SupplierName}");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"检查进货单时异常: {ex.Message}");
                        return false;
                    }
                }

                // 2. 检查退货明细中的进货明细ID是否有效
                foreach (var detail in createDto.ReturnOrderDetails)
                {
                    Console.WriteLine($"检查明细: ID={detail.PurchaseOrderItemId}, 数量={detail.ReturnNumber}, 金额={detail.ReturnMoney}");
                    
                    if (detail.PurchaseOrderItemId <= 0)
                    {
                        Console.WriteLine($"验证失败: 进货明细ID {detail.PurchaseOrderItemId} 无效");
                        return false;
                    }

                    if (detail.ReturnNumber <= 0)
                    {
                        Console.WriteLine($"验证失败: 退货数量 {detail.ReturnNumber} 必须大于0");
                        return false;
                    }

                    if (detail.ReturnMoney <= 0)
                    {
                        Console.WriteLine($"验证失败: 退货金额 {detail.ReturnMoney} 必须大于0");
                        return false;
                    }
                    
                    // 处理备注字段
                    if (string.IsNullOrEmpty(detail.Remarks))
                    {
                        detail.Remarks = "";
                        Console.WriteLine("备注为空，设置为空字符串");
                    }
                }

                // 处理退货单备注字段
                if (string.IsNullOrEmpty(createDto.ReturnOrder.Remarks))
                {
                    createDto.ReturnOrder.Remarks = "";
                    Console.WriteLine("退货单备注为空，设置为空字符串");
                }

                Console.WriteLine("所有验证通过，调用Repository层");
                // 调用仓储层的事务方法
                var result = await _repository.AddWithDetailsAsync(createDto);
                Console.WriteLine($"Repository层执行结果: {result}");
                
                return result;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Service层异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                return false;
            }
        }
    }
}